package com.wjd.store;

import com.wjd.config.Constants;
import com.wjd.parser.PageInfo;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 数据存储器
 *
 * @author weijiaduo
 * @since 2024/3/18
 */
public class Store {

    private static final Store INSTANCE = new Store();

    /**
     * 页面树
     */
    private final PageStore pageStore;
    /**
     * 词语树
     */
    private final WordStore wordStore;

    public static Store getInstance() {
        return INSTANCE;
    }

    private Store() {
        try {
            pageStore = new PageStore(Constants.PAGE_PATH);
            wordStore = new WordStore(Constants.WORD_PATH);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询多个关键字，输出一个Results数组
     *
     * @param words 关键字集合
     * @return 结果集合
     */
    public QueryResult[] query(Set<String> words) {
        int n = words.size(), i = 0;
        QueryResult[] results = new QueryResult[n];
        for (String word : words) {
            List<WordRecord> wordRecords = wordStore.queryByKey(word);
            if (wordRecords.isEmpty()) {
                System.out.println("关键字" + word + "不在数据库中");
                results[i++] = new QueryResult(word, null);
                continue;
            }
            List<Sample> samples = wordRecords.stream().map(wr -> {
                long pageId = wr.getPageId();
                List<PageRecord> prs = pageStore.queryById(pageId);
                if (prs.isEmpty()) {
                    return null;
                }
                PageRecord pr = prs.get(0);
                return new Sample(pr.getUrl(), pr.getPageValue(),
                        pr.getTitle(), pr.getContent(), wr.getTf(), wr.isTitled());
            }).filter(Objects::nonNull).toList();
            results[i++] = new QueryResult(word, samples);
        }
        return results;
    }

    /**
     * 插入一条新数据
     *
     * @param pageInfo 页面信息数据
     * @return true 插入成功；false 插入失败
     */
    public boolean insert(PageInfo pageInfo) {
        String url = pageInfo.getUrl();
        int pv = pageInfo.getPageValue();
        String title = pageInfo.getTitle();
        String content = pageInfo.getContent();

        // 保存页面信息
        PageRecord pageRecord = new PageRecord(url, pv, title, content);
        long pageId = pageStore.save(pageRecord);

        // 保存标题词语信息
        for (Map.Entry<String, Double> e : pageInfo.getTitleTF().entrySet()) {
            String word = e.getKey();
            Double tf = e.getValue();
            WordRecord record = new WordRecord(word, pageId, pv, tf, true);
            wordStore.save(record);
        }

        // 保存正文词语信息
        for (Map.Entry<String, Double> e : pageInfo.getContentTF().entrySet()) {
            String word = e.getKey();
            Double tf = e.getValue();
            WordRecord record = new WordRecord(word, pageId, pv, tf, false);
            wordStore.save(record);
        }
        return true;
    }

}
